interface ImageSize {
  width: number;
  height: number;
}
import { createRandomCode } from '@/utils/common'
import ObsClient from 'esdk-obs-browserjs'
// const ObsClient = require('@/plugins/esdk-obs-browserjs-without-polyfill-3.19.9.min.js')
const obsClient: any = new ObsClient({
  access_key_id: "BDWBBLL8S92BE2ANMT3K",
  secret_access_key: "vu9OeRPLD2Zsgci8ArcTLIO816IBEN9gwZaayjlr",
  server: "https://obs.cn-north-4.myhuaweicloud.com",
})
/**
 * 
 *  base64转文件
 */
 export const base64toFile = (dataBase64: any, filename: any) => {
  const arr = dataBase64.split(",");
  const mime = arr[0].match(/:(.*?);/)[1]; //设置file文件流的type名称
  const suffix = mime.split("/")[1]; //设置file文件流的name名称
  console.log(arr[0]);
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime,
  });
}
/**
 * 
 *  base64图片上传华为云返回图片url
 */
export const base64ToUrl = (base64: any) => {  //缩略图转url
  return new Promise(resolve => {
    if (!base64.startsWith('http')) {
      const file = base64toFile(base64, 'ThumbnailImg' + createRandomCode());
      obsClient.putObject(
        {
          Bucket: "vrar-obs-production", // 不做修改
          Key: "ssc-develop/ppt/" + "用户ID" + "/" + file.name,
          SourceFile: file,
          ACL: obsClient.enums.AclPublicRead, // 不做修改
        },
        function (err: any, result: any) {
          if (err) {
            // 失败重新上传
            console.log(err);
            base64ToUrl(base64)
          } else {
            // 上传后的文件地址
            const appName = "ppt"; // 只能为英文
            const fileUrl =
              "https://vrar-obs-production.obs.cn-north-4.myhuaweicloud.com/ssc-develop/" +
              appName +
              "/" +
              "用户ID" +
              "/" +
              file.name;
            // 按需求自己编写
            // console.log(fileUrl,'-----------urlthumbnailImg-----------------');
            resolve(fileUrl)
          }
        }
      );
    }
  })


}
/**
 * 获取图片的原始宽高
 * @param src 图片地址
 */
export const getImageSize = (src: string, size: number): Promise<ImageSize> => {
  return new Promise(resolve => {
    if (size < 100000) {
      const img = document.createElement('img')
      img.src = src
      img.style.opacity = '0'
      document.body.appendChild(img)

      img.onload = () => {
        const imgWidth = img.clientWidth
        const imgHeight = img.clientHeight

        img.onload = null
        img.onerror = null

        document.body.removeChild(img)

        resolve({ width: imgWidth, height: imgHeight })
      }

      img.onerror = () => {
        img.onload = null
        img.onerror = null
      }

    } else {
      resolve({ width: 400, height: 300 })
    }
    // const img = document.createElement('img')
    // img.src = src
    // // img.style.opacity = '0'
    // document.body.appendChild(img)



    // img.onload = () => {
    //   console.log("getImageSize onload")

    //   const imgWidth = img.clientWidth
    //   const imgHeight = img.clientHeight

    //   img.onload = null
    //   img.onerror = null

    //   document.body.removeChild(img)

    // }

    // img.onerror = () => {
    //   img.onload = null
    //   img.onerror = null
    // }
  })
}

/**
 * 读取图片文件的dataURL
 * @param file 图片文件
 */
export const getImageDataURL = (file: File): Promise<string> => {
  return new Promise(resolve => {
    const reader = new FileReader()
    reader.addEventListener('load', () => {
      resolve(reader.result as string)
    })
    reader.readAsDataURL(file)
  })
}
/**
 * 获取图片的原始宽高
 * @param src 图片地址
 */
 export const getImageSize2 = (src: string): Promise<ImageSize> => {
  return new Promise(resolve => {
    const img = document.createElement('img')
    img.src = src
    img.style.opacity = '0'
    document.body.appendChild(img)

    img.onload = () => {
      const imgWidth = img.clientWidth
      const imgHeight = img.clientHeight
    
      img.onload = null
      img.onerror = null

      document.body.removeChild(img)

      resolve({ width: imgWidth, height: imgHeight })
    }

    img.onerror = () => {
      img.onload = null
      img.onerror = null
    }
  })
}
/**
 * 
 */
export const urlToBase64 = (url: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    const image = new Image()
    let width: any = 0, height: any = 0
    getImageSize2(url).then((res) => {
      width = res.width
      height = res.height
    })
    image.onload = function () {
      const canvas: any = document.createElement('canvas')
      canvas.width = width
      canvas.height = height
      // 将图片插入画布并开始绘制
      canvas.getContext('2d').drawImage(image, 0, 0)
      // result
      const result = canvas.toDataURL('image/png')
      resolve(result)
    }
    // CORS 策略，会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
    image.setAttribute("crossOrigin", 'Anonymous')
    image.src = url + "?id=" +Date.now()
    // 图片加载失败的错误处理
    image.onerror = () => {
      reject(new Error('urlToBase64 error'))
    }
  })
}